package com.woniu.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woniu.entity.Result;
import com.woniu.shop.constant.RedisConstant;
import com.woniu.shop.entity.dto.CashOutDTO;
import com.woniu.shop.entity.dto.EditShopMesDTO;
import com.woniu.shop.entity.dto.ShopLoginDTO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.PageResult;
import com.woniu.shop.pojo.Shop;
import com.woniu.shop.mapper.ShopMapper;
import com.woniu.shop.pojo.Shop;
import com.woniu.shop.entity.dto.ShopDTO;
import com.woniu.shop.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.shop.utils.JwtUtil;
import com.woniu.util.RegularUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 门店表 服务实现类
 * </p>
 *
 * @author LiFangyu
 * @since 2023-02-15
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired(required = false)
    private ShopMapper shopMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Map<String, Object> shopLogin(ShopLoginDTO shopLoginDTO) {
        LambdaQueryWrapper<Shop> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(shopLoginDTO.getAccount()), Shop::getAccount, shopLoginDTO.getAccount());
        Shop shop = shopMapper.selectOne(wrapper);
        if(shop == null){
            return null;
        }
        // 判断用户密码是否正确
        if(!BCrypt.checkpw(shopLoginDTO.getLoginPwd(),shop.getLoginPwd())){
            return null;
        }
        // 运行至此，登录成功，生成token
        Map<String, Object> shopMessage = new HashMap<>();
        shopMessage.put("shopName", shop.getShopName());
        shopMessage.put("shopAddress", shop.getShopAddress());
        shopMessage.put("shopDescription", shop.getShopDescription());
        shopMessage.put("shopPhone", shop.getShopPhone());
        shopMessage.put("businessLicenseNum", shop.getBusinessLicenseNum());
        shopMessage.put("businessTime", shop.getBusinessTime());
        String token = JwtUtil.createJWT(shop.getId(), shopMessage, 30 * 60 * 60L);
        stringRedisTemplate.opsForValue().set(RedisConstant.SHOP_LOGIN_TOKEN.name() + "_" + shop.getId(), token,30 * 60, TimeUnit.SECONDS);
        shopMessage.put("Authorization", token);
        return shopMessage;
    }

    @Override
    public int editShopMessage(EditShopMesDTO editShopMesDTO) {
        Shop shop = new Shop();
        BeanUtils.copyProperties(editShopMesDTO, shop);
        // 对密码进行加密
        String salt = BCrypt.gensalt();
        String hashPwd = BCrypt.hashpw(editShopMesDTO.getTradePwd(), salt);
        shop.setTradePwd(hashPwd);
        return shopMapper.updateById(shop);
    }

    @Override
    public PageResult<Shop> querySearch(Integer currentPage, Integer pageSize, ShopDTO shopDTO) {
        // 1. 构建查询条件
        LambdaQueryWrapper<Shop> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(!StringUtils.isEmpty(shopDTO.getShopName()),Shop::getShopName, shopDTO.getShopName());
        wrapper.like(!StringUtils.isEmpty(shopDTO.getShopAddress()),Shop::getShopAddress, shopDTO.getShopAddress());
        // 2. 构建分页对象
        IPage<Shop> page = new Page<>(currentPage, pageSize);
        // 3. 调用mapper查询数据
        IPage<Shop> selectPage = shopMapper.selectPage(page, wrapper);
        // 4. 封装pageResult对象
        PageResult<Shop> pageResult = new PageResult<>(selectPage.getTotal(), selectPage.getRecords());
        // 5. 返回数据
        return pageResult;
    }

    @Override
    public Result<Object> cashOut(CashOutDTO cashOutDTO) {
        if(cashOutDTO.getShopPhone() == null){
            return Result.error("手机号码不能为空");
        }
        if(!RegularUtil.regularPhoneNumber(cashOutDTO.getShopPhone())){
            return Result.error("手机号码格式不正确，请重新输入");
        }
        if(cashOutDTO.getAmount().compareTo(new BigDecimal(0)) <= 0){
            return Result.error("提现金额必须大于0元");
        }
        // 根据门店id查询并验证绑定手机号和密码
        LambdaQueryWrapper<Shop> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(cashOutDTO.getShopId()), Shop::getId, cashOutDTO.getShopId());
        wrapper.eq(!StringUtils.isEmpty(cashOutDTO.getShopPhone()), Shop::getShopPhone, cashOutDTO.getShopPhone());
        Shop shop = shopMapper.selectOne(wrapper);
        if(shop == null){
            return Result.error("请正确输入门店绑定的手机号");
        }
        if(!BCrypt.checkpw(cashOutDTO.getTradePwd(),shop.getTradePwd())){
            return Result.error("交易密码不正确");
        }
        if(cashOutDTO.getAmount().compareTo(shop.getBalance()) > 0){
            return Result.error("提现失败，账户余额不足");
        }
        // 更新账户余额
        shop.setBalance(shop.getBalance().subtract(cashOutDTO.getAmount()));
        int row = shopMapper.updateById(shop);
        if(row == 0){
            return Result.error("提现失败，网络出错了，请稍后重试");
        }
        return Result.ok("提现成功，账户余额为：" + shop.getBalance());
    }


}
